package com.ext.aic.adapter;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

import com.ext.aic.R;
import com.ext.aic.beans.MenuItem;
import com.ext.aic.databinding.MenuItemViewBinding;
import com.ext.aic.holder.MenuViewHolder;
import com.eyinfo.android_pure_utils.events.Action1;
import com.eyinfo.android_pure_utils.utils.ConvertUtils;

import java.util.List;

import lombok.Setter;

public class MenuAdapter extends RecyclerView.Adapter<MenuViewHolder> {

    private List<MenuItem> items;
    @Setter
    private Action1<MenuItem> itemClickCall;

    public MenuAdapter(List<MenuItem> items) {
        this.items = items;
    }

    @Override
    public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.menu_item_view, parent, false);
        return new MenuViewHolder(MenuItemViewBinding.bind(view));
    }

    @Override
    public void onBindViewHolder(MenuViewHolder holder, int position) {
        MenuItem styleItem = items.get(position);
        holder.textTv.setText(styleItem.getName());
        holder.menuItemRl.setOnClickListener(this::onItemClick);
        holder.menuItemRl.setTag(position);
        holder.menuItemRl.setSelected(styleItem.isCheck());
        holder.textTv.setTextColor(styleItem.isCheck() ? Color.WHITE : 0xff333333);
    }

    @SuppressLint("NotifyDataSetChanged")
    public void onItemClick(View view) {
        clearCheck();
        int position = ConvertUtils.toInt(view.getTag());
        MenuItem item = items.get(position);
        item.setCheck(true);
        super.notifyDataSetChanged();
        if (itemClickCall != null) {
            itemClickCall.call(item);
        }
    }

    private void clearCheck() {
        for (MenuItem item : items) {
            item.setCheck(false);
        }
    }

    @Override
    public int getItemCount() {
        return items.size();
    }
}
